package com.xckj.cycling.framework;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.xckj.cycling.R;

/**
 * @Author: ChenYao
 * @Describe: Activity的基类
 * @Date: 2023/2/25 22:02
 */
public abstract class BaseActivity<T extends ViewDataBinding> extends BaseActivityKt implements View.OnClickListener, IBaseView {
    protected T dataBinding;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        dataBinding = DataBindingUtil.setContentView(this, loadLayout());
        notifyViewBinding();
    }


    /**
     * 加载布局文件
     *
     * @return 布局文件
     */
    abstract protected int loadLayout();

    @Override
    protected void setTitle() {
        View ivBack = findViewById(R.id.btn_back);
        if (null != ivBack) {
            ivBack.setOnClickListener(v -> finish());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            hideKeyboard(ev, view, BaseActivity.this);
        }
        return super.dispatchTouchEvent(ev);

    }

    public static void hideKeyboard(MotionEvent event, View view, Activity activity) {
        try {
            if (view instanceof EditText) {
                int[] location = {0, 0};
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left + view.getWidth(), bootom = top + view.getHeight();
                // （判断是不是EditText获得焦点）判断焦点位置坐标是否在控件所在区域内，如果位置在控件区域外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
